﻿
using Fleck;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace XCool.CommonApp
{
    public class WebSocket
    {
        public static void Init()
        {
            var allScokets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://127.0.0.1:9898");    //创建webscoket服务端实例
            server.Start(scoket =>
            {

                scoket.OnOpen = () =>
                {
                    Console.WriteLine("Open");
                    allScokets.Add(scoket);
                };
                scoket.OnClose = () =>
                {
                    Console.WriteLine("Close");
                    allScokets.Remove(scoket);
                };
                scoket.OnMessage = message =>
                {
                    Console.WriteLine(message);
                    allScokets.ToList().ForEach(s => s.Send("已经接收到:" + message));
                };

                scoket.OnPing = msg =>
                {
                    Console.WriteLine(msg);
                };
                scoket.OnPong = msg =>
                {
                    Console.WriteLine(msg);
                };

                scoket.OnError = msg => {
                    Console.WriteLine(msg);
                };

                scoket.OnBinary = msg =>
                {
                    Console.WriteLine(msg);
                };
            });

            var input = Console.ReadLine();
            while (input != "exit")
            {
                foreach (var socket in allScokets.ToList())
                {
                    socket.Send("服务端：" + input);
                }
                input = Console.ReadLine();
            }

        }
    }
}